<!--  -->
<template>
  <div class>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-button type="primary" class="mtb10" @click="addRolesDialogVisible = true">添加角色</el-button>
      <!-- 表格 -->
      <el-table stripe border :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div class="expandContainer">
              <!-- 一级菜单 -->
              <el-row
                :class="['lever_center','bdbottom',index==0?'dbtop1':'']"
                v-for="(lever1,index) in scope.row.children"
                :key="index"
              >
                <el-col :span="6">
                  <el-tag closable @close="removeUserRole(scope.row,lever1)">{{lever1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <!-- 二级菜单 -->
                  <el-row
                    v-for="(lever2,index) in lever1.children"
                    :key="index"
                    :class="['lever_center',index== lever1.children.length-1 ?'':'bdbottom']"
                  >
                    <el-col :span="6">
                      <el-tag
                        class="m7"
                        closable
                        @close="removeUserRole(scope.row,lever2)"
                      >{{lever2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级菜单 -->
                    <el-col :span="18" class="lever3_box">
                      <el-row v-for="(lever3,index) in lever2.children" :key="index">
                        <el-tag
                          class="m7"
                          closable
                          @close="removeUserRole(scope.row,lever3)"
                        >{{lever3.authName}}</el-tag>
                      </el-row>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
            <!-- 用于展示json数据 -->
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="getRoleForm(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeRole(scope.row.id)"
            >删除</el-button>
            <el-tooltip effect="dark" content="设置角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="getRoleTree(scope.row)"
              >设置权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑用户dialog -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" @closed="eidtFormReset">
      <el-form ref="form" :model="roleForm" label-width="85px" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.roleDesc" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 展示权限数dialog -->
    <el-dialog title="设置权限" :visible.sync="setRolesDialogVisible">
      <el-tree
        ref="roleTree"
        :data="rightsTree"
        :props="treeProps"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultKeys"
        node-key="id"
      ></el-tree>
      <div slot="footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加角色dialog -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialogVisible">
      <el-form :model="addRuleForm" :rules="rules" ref="addRuleForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  name: 'HomeRoles',
  components: {},
  data() {
    return {
      roleForm: { roleName: '', roleDesc: '', id: '' },
      addRuleForm: { roleName: '', roleDesc: '' },
      rolesList: null,
      rightsTree: null,
      defaultKeys: [],
      editDialogVisible: false,
      setRolesDialogVisible: false,
      addRolesDialogVisible: false,
      rolesListInfo: {},
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述信息', trigger: 'blur' }
        ]
      },
      treeProps: { children: 'children', label: 'authName' }
    }
  },
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getRolesList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  methods: {
    async getRolesList() {
      let { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    async removeUserRole(role, right) {
      let { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${right.id}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      role.children = res.data
      this.$message.success(res.meta.msg)
    },
    getRoleForm(role) {
      this.roleForm.roleName = role.roleName
      this.roleForm.roleDesc = role.roleDesc
      this.roleForm.Id = role.id
      this.editDialogVisible = true
    },
    eidtFormReset() {
      this.$refs.form.resetFields()
    },
    editRoleForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.put(
          'roles/' + this.roleForm.Id,
          this.roleForm
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    removeRole(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let { data: res } = await this.$http.delete('roles/' + id)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.getRolesList()
          this.$message.success(res.meta.msg)
        })
        .catch(() => {
          this.$message.info('取消删除成功')
        })
    },
    async getRoleTree(data) {
      this.roleInfo = data
      this.defaultKeys = []
      this.getCheckedListID(data.children)
      let { data: res } = await this.$http.get('rights/tree')
      this.rightsTree = res.data
      this.setRolesDialogVisible = true
    },
    getCheckedListID(data) {
      //如果没有children属性，就将他的id放到defaultKeys里边,否则继续递归
      data.forEach(item => {
        if (!item.children) return this.defaultKeys.push(item.id)
        this.getCheckedListID(item.children)
      })
    },
    async setRoles() {
      let ids = [
        ...this.$refs.roleTree.getHalfCheckedKeys(),
        ...this.$refs.roleTree.getCheckedKeys()
      ]
      let str = ids.join(',')
      let { data: res } = await this.$http.post(
        `roles/${this.roleInfo.id}/rights`,
        {
          rids: str
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.setRolesDialogVisible = false
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    saveRole() {
      this.$refs.addRuleForm.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.post('roles', this.addRuleForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addRolesDialogVisible = false
        this.getRolesList()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.lever_center {
  display: flex;
  align-items: center;
}
.lever3_box {
  display: flex;
  flex-wrap: wrap;
}
</style>